var chinaMap = function() {
	this.canvas = document.getElementById("canvas_china");
	this.ctx = this.canvas.getContext("2d");
	this.datajson = ""; //返回数据
	this.scaleData = 1.0; //放大系数
	this.tranX = 0; //x移动系数
	this.tranY = 0; //y移动系数
	this.width = 0; //宽
	this.height = 0;
	this.w_center = 0; //中心点
	this.h_center = 0;
	this.mapCenter = [105,40],//地图绘制的中心点经纬度
	this.scale_bi =( 330 / 197); //缩放大地图的
	this.drawWaitTime = 0;
	this.start = []; //手指缩放位置
	this.startX = 0; //开始x的位置
	this.startY = 0; //开始y的位置
	this.projection = ""; //大陆d3 投影计算
	this.H_projection = ""; //海南的投影计算
	this.myMapGeo="";//百度地图实例化 
	
	//自定义移动缩放事件
	// if (this.canvas.addEventListener) {
	// 	this.canvas.addEventListener("touchstart", this.scaleCanvasPhoneStart.bind(this));
	// 	this.canvas.addEventListener("touchmove", this.scaleCanvasPhoneMove.bind(this));
	// 	// IE9, Chrome, Safari, Opera
	// 	this.canvas.addEventListener("mousewheel", this.scaleCanvas.bind(this), false);
	// 	// Firefox
	// 	this.canvas.addEventListener("DOMMouseScroll", this.scaleCanvas.bind(this), false);
	// } else {
	// 	// IE 6/7/8
	// 	this.canvas.attachEvent("onmousewheel", this.scaleCanvas.bind(this));
	// }
	if(this.canvas.addEventListener){
		this.canvas.addEventListener("click",this.onClickPoint.bind(this));
	}
	this.H_width = 0; //海南诸岛绘制宽
	this.H_height = 0; //海南诸岛绘制高
	this.H_w_center = 0; //海南诸岛宽中心
	this.H_h_center = 0; //海南诸岛高中心
	this.H_x = 0; //海南x
	this.H_y = 0;
}
chinaMap.prototype.init = function() {
	if (this.datajson == "") {
		this.loadjson();
		return;
	}
	this.provinces = [];
	this.provincesHainan = [];
 
	let scale = this.scale_bi * this.w_center;
	//center 为地图中心的经纬度参数
	let hscale_bi = 130 /27.6; //海南诸岛的比例
	let hscal = hscale_bi * this.H_h_center;
	this.projection = d3.geoMercator().center(this.mapCenter).scale(scale).translate([this.w_center, this.h_center]);
	this.H_projection = d3.geoMercator().center([114, 13]).scale(hscal).translate([this.H_w_center, this
		.H_h_center
	]);

	this.datajson.features.forEach(elem => {
		//获得的每个省级单位
		const adcode = elem.properties.adcode;
		//中心点
		let center = [];
		let centerid = [];
		try {
			if (adcode == "100000_JD" || adcode == "460000") {
				//投影到canvas坐标
				center = this.H_projection(elem.properties.center);
				centerid = this.H_projection(elem.properties.centroid);
			} else {
				//投影到canvas坐标
				center = this.projection(elem.properties.center);
				centerid = this.projection(elem.properties.centroid);
			}

		} catch (e) {
			console.log("log: error", elem.properties.name,elem);
		}
		const provice = {
			"name": elem.properties.name, //名字
			"adcode": adcode, //
			"center": center,
			"centeroid":centerid,
			"points": [],
			"isselect":false,
		};
		//坐标点
		const coordinates = elem.geometry.coordinates;
		coordinates.forEach(multiPolygon => {
			if (adcode == 150000) { //内蒙古geo坐标没有二级
				const points = [];
				for (var i = 0; i < multiPolygon.length; i++) {
					const point = this.projection(multiPolygon[i]);
					points.push(point);
				}
				provice.points.push(points);
			} else {
				const points = [];
				multiPolygon.forEach(polygon => {
					for (var i = 0; i < polygon.length; i++) {
						if (adcode == "100000_JD" || adcode == "460000") {
							const point = this.H_projection(polygon[i]);
							points.push(point);
						} else {
							const point = this.projection(polygon[i]);
							points.push(point);
						}
					}
				});
				provice.points.push(points);
			}
		});
		if (adcode == "100000_JD" || adcode == "460000") { //九段线和海南诸岛
			this.provincesHainan.push(provice);
		} else {
			this.provinces.push(provice);
		}

	});
	this.redraw();
}



chinaMap.prototype.draw = function() {
	// this.drawWaitTime += deltaTime;
	// if (this.drawWaitTime < 1000) {
	// 	return
	// }
	// this.drawWaitTime = 0;
}


chinaMap.prototype.redraw =function(){
	 this.ctx.clearRect(0,0,this.width,this.height);
	this.drawMap(this.ctx); //大陆
	this.drawHanNan(this.ctx); //海南诸岛
}





//绘制地图
chinaMap.prototype.drawMap = function(ctx) {

	this.provinces.forEach(porvince => {
		// console.log("省份 ", porvince.name);
		// console.log("数据 ", porvince.adcode);
		// console.log("数据点 ", porvince.points);
		ctx.save();
		if(porvince.isselect){//是否选中
			ctx.strokeStyle = "#FFA50077";
			ctx.fillStyle = "#FFA50088";
		}else{
			ctx.strokeStyle = "#1ec0ff";
			ctx.fillStyle = "#1ec0ff99";
		}
		ctx.lineWidth = 0.5;
		ctx.beginPath();
		if (porvince.adcode == "100000_JD" || porvince.adcode == "460000") { //九段线
			return;
		}
		porvince.points.forEach(multiPolygon => {

			for (var i = 0; i < multiPolygon.length; i++) {
				if (i == 0) {
					ctx.moveTo(multiPolygon[i][0], multiPolygon[i][1]);
				} else {
					ctx.lineTo(multiPolygon[i][0], multiPolygon[i][1]);
				}
			}
			 
		});
		ctx.closePath();
		ctx.fill();
		ctx.stroke();
		ctx.font="5px STSong";
		ctx.textBaseline = 'left'; //设置文本的垂直对齐方式
		ctx.textAlign = 'center';//设置文本的水平对齐方式
		if(porvince.isselect){
			ctx.fillStyle = "#ffffff";
		}else{
			ctx.fillStyle = "#ffffff66";
		}
		//绘制地图省会位置
		let centers = porvince.center;
		for (var i = 0; i < centers.length; i++) {
			ctx.beginPath();
			//省会坐标点
			// ctx.arc(centers[0], centers[1], 1, 0, 2 * Math.PI);
			ctx.fillText(porvince.name,centers[0], centers[1]);
			ctx.fill();
		}
		
		
		
		ctx.restore();
	})
}

//海南诸岛
chinaMap.prototype.drawHanNan = function(ctx) {

	ctx.save();
	ctx.beginPath();
	ctx.strokeStyle = "#1ec0ff99"
	ctx.lineWidth = 2;
	ctx.rect(this.H_x, this.H_y, this.H_width, this.H_height);
	ctx.stroke();
	ctx.restore();

	this.provincesHainan.forEach(porvince => {
		 console.log("H省份 ", porvince.name);
		console.log("H数据 ", porvince);
		 
		ctx.save();
		if(porvince.isselect){//是否选中
			ctx.strokeStyle = "#FFA50077";
			ctx.fillStyle = "#FFA50088";
		}else{
			ctx.strokeStyle = "#1ec0ff";
			ctx.fillStyle = "#1ec0ff99";
		}
		ctx.lineWidth = 0.5;
		ctx.beginPath();
		porvince.points.forEach(multiPolygon => {
			for (var i = 0; i < multiPolygon.length; i++) {
				if (i == 0) {
					ctx.moveTo(multiPolygon[i][0] + this.H_x, multiPolygon[i][1] + this.H_y);
				} else {
					ctx.lineTo(multiPolygon[i][0] + this.H_x, multiPolygon[i][1] + this.H_y);
				}
			}
		});
		ctx.closePath();
		ctx.fill();
		ctx.stroke();
		
		ctx.font="8px STSong";
		ctx.textBaseline = 'bottom'; //设置文本的垂直对齐方式
		ctx.textAlign = 'center';//设置文本的水平对齐方式
		if(porvince.isselect){
			ctx.fillStyle = "#ffffff";
		}else{
			ctx.fillStyle = "#ffffff66";
		}
		
		ctx.beginPath();
		//省会坐标
		ctx.fillText(porvince.name,this.H_w_center+this.H_x, this.H_height+this.H_y);
		ctx.fill();
		//绘制地图省会位置
		// let centers = porvince.centerid;
		// for (var i = 0; i < centers.length; i++) {
		// 	ctx.beginPath();
		// 	//省会坐标
		// 	// ctx.arc(centers[0]+this.H_x, centers[1]+this.H_y, 1, 0, 2 * Math.PI);
		// 	ctx.fillText("海南诸岛",this.H_w_center+this.H_x, this.H_height+this.H_y);
		// 	ctx.fill();
		// }
		ctx.restore();
	})


}


chinaMap.prototype.size = function() {
	this.canvasRect = this.canvas.getBoundingClientRect();
	let scales = window.devicePixelRatio; //
	this.width = this.canvasRect.width;
	this.height = this.canvasRect.height;

	this.canvas.style.width = this.width + "px";
	this.canvas.style.height = this.height + "px";
	this.canvas.width = this.width * scales;
	this.canvas.height = this.height * scales;

	this.w_center = this.width / 2;
	this.h_center = this.height / 2;
	this.ctx.scale(scales, scales);

	
	this.H_height = (this.height / 5)>100?100:(this.height / 5);
	// this.H_width = this.width / 6;
	this.H_width = this.H_height*0.8;
	this.H_w_center = this.H_width / 2;
	this.H_h_center = this.H_height / 2;
	this.H_x = this.width - this.H_width;
	this.H_y = this.height - this.H_height;



}


//获取json数据
chinaMap.prototype.loadjson = function() {
	const that = this;
	var xhr = new XMLHttpRequest();
	xhr.open("GET", "../js/china.json", true);
	xhr.send();
	xhr.onreadystatechange = function() {
		if (xhr.readyState == 4 && xhr.status == 200) {
			console.log("请求完成了: ", that.datajson);
			that.datajson = JSON.parse(xhr.responseText);
			that.init();

		}
	}
}


//点击
chinaMap.prototype.onClickPoint = function(event){
	
	let x = event.offsetX;
	let y = event.offsetY;
	console.log("x y ",x,y);
	console.log("Hx Hy ",this.H_x,this.H_y);
	if(x>this.H_x && y>this.H_y){
		 
		//海南诸岛
		for(var i=0;i<this.provincesHainan.length;i++){
			let isSelect = this.provincesHainan[i].isselect;
			this.provincesHainan[i].isselect = !isSelect;
		}
		this.redraw();
		return;
	}
	
	
	
	if(this.myMapGeo==""){
		this.myMapGeo = new BMapGL.Geocoder(); 
	}
	let outPoint =  this.projection.invert([x,y]);
	console.log("outPint ",outPoint);
	console.log("this.myMapGeo ",this.myMapGeo);
	 let that =this;
	this.myMapGeo.getLocation(new BMapGL.Point(outPoint[0],outPoint[1]),(res)=>{
		 try{
			
			 let province = res.addressComponents.province;
			  console.log("省份Start",province);
			 if(province==""){
				 return;
			 }
			 province = province.replace("省","");
			 province = province.replace("维吾尔","");
			 province = province.replace("自治区","");
			 province = province.replace("特别行政区","");
			 province = province.replace("壮族","");
			 console.log("省份 ",province);
			 that.selectProvince.call(that,province); 
		 }catch(e){
			 console.log("error ",e);
		 }
	})
}

//点中哪些省份
chinaMap.prototype.selectProvince=function(name){
	let provinceLength = this.provinces.length;
	console.log(name," data: ",this.provinces);
	for(var i=0;i<provinceLength;i++){
		console.log("省份: ",this.provinces[i], name);
		if(this.provinces[i].name == name){
			let isSelect = this.provinces[i].isselect;
			this.provinces[i].isselect = !isSelect;
			this.redraw();
			break;
		}
	}
}


//鼠标滚轮
chinaMap.prototype.scaleCanvas = function(event) {
	event.preventDefault();
	var e = window.event || event; // old IE support
	var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
	console.log(delta + "->" + e.wheelDelta + '->' + e.detail);
	this.scalexy(delta);

}
chinaMap.prototype.scaleCanvasPhoneStart = function(e) {
	e.preventDefault();
	if (e.touches.length == 1) {
		this.startX = e.touches[0].pageX;
		this.startY = e.touches[0].pageY;
	}
	if (e.touches.length >= 2) {
		this.start = e.touches;
	}

}

//手机双指缩放 单指移动
chinaMap.prototype.scaleCanvasPhoneMove = function(e) {
	e.preventDefault();
	// console.log("几根手指",e.touches.length);
	//移动
	if (e.touches.length == 1) {
		let nowX = e.touches[0].pageX;
		let movesx = nowX - this.startX;
		this.startX = nowX;
		console.log("x移动的距离 ", movesx)
		if (movesx > 0) {
			//右移
			this.tranx(1);
		} else if (movesx < 0) {
			//左移
			this.tranx(-1);
		}
		let nowY = e.touches[0].pageY;
		let movesy = nowY - this.startY;
		this.startY = nowY;
		console.log("y移动的距离 ", movesy);
		if (movesy > 0) {
			this.trany(1);
		} else if (movesy < 0) {
			this.trany(-1);
		}



	};
	//缩放
	if (e.touches.length >= 2) {
		//得到两个点
		var now = e.touches;
		// console.log("e.touches ",e.touches);
		//缩小
		if (this.getDistance(now[0], now[1]) < this.getDistance(this.start[0], this.start[1])) {
			this.scalexy(-1);
		} else { //放大
			this.scalexy(1);
		}


	}

}
//设置放大倍数
chinaMap.prototype.scalexy = function(delta) {
	if (delta == -1) {
		this.scaleData -= 0.05;
		if (this.scaleData < 0.3) {
			this.scaleData = 0.3
		}
	} else {
		this.scaleData += 0.05;
		if (this.scaleData > 3) {
			this.scaleData = 3
		}
	}
	// console.log("发达缩小的 ",this.scaleData);
	vue.canvasScaleF(this.scaleData);
	// console.log("缩放",this.scaleData);
	// //this.ctx.translate(this.w_center,this.h_center);
	// this.ctx.scale(this.scaleData,this.scaleData);
	// //this.ctx.translate(-(this.w_center/this.scaleData),-(this.h_center/this.scaleData));
	// this.ctx.clearRect(0,0,this.width,this.height);
	// this.drawMap(this.ctx);
}
//水平移动
chinaMap.prototype.tranx = function(tran) {
	if (tran == -1) {
		this.tranX -= 5;
		if (this.tranX < -this.w_center) {
			this.tranX = -this.w_center;
		}
	} else {
		this.tranX += 5;
		if (this.tranX > this.w_center) {
			this.tranX = this.w_center;
		}
	}
	vue.canvasLeft(this.tranX);
}
//垂直移动
chinaMap.prototype.trany = function(tran) {
	if (tran == -1) {
		this.tranY -= 5;
		if (this.tranY < -this.h_center) {
			this.tranY = -this.h_center;
		}
	} else {
		this.tranY += 5;
		if (this.tranY > this.w_center) {
			this.tranY = this.w_center;
		}
	}
	vue.canvasTop(this.tranY);
}
//复原
chinaMap.prototype.recovery = function() {
	this.scaleData = 1.0; //放大系数
	this.tranX = 0; //x移动系数
	this.tranY = 0; //y移动系数
	vue.canvasScaleF(this.scaleData);
	vue.canvasLeft(this.tranX);
	vue.canvasTop(this.tranY);

}


//计算公式
chinaMap.prototype.getDistance = function(p1, p2) {
	var x = p2.pageX - p1.pageX,
		y = p2.pageY - p1.pageY;
	return Math.sqrt((x * x) + (y * y));
}
